from rest_framework.views import APIView
from django.http.response import HttpResponse
import logging, base64, json, requests, datetime
from django.conf import settings
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

from wxapi.utils import get_sign_sha1, pkcs7_padding_encoder, wyf_access_token
from equity_mall.utils.utils import trans_xml_to_dict, bind_customer
from users.models import CustomerUserVice

logger = logging.getLogger('wxapi')


class WXPublicAccountMessageView(APIView):

    def get(self, request, format=None):
        # 接收微信服务器get请求发过来的参数
        signature = request.GET.get('signature', None)
        timestamp = request.GET.get('timestamp', None)
        nonce = request.GET.get('nonce', None)
        echostr = request.GET.get('echostr', None)
        wechat_token = settings.WECHAT_TOKEN
        logger.info(f'{signature},{timestamp},{nonce},{echostr}')
        check_sign = get_sign_sha1([timestamp, nonce, wechat_token])
        if signature == check_sign:
            return HttpResponse(echostr)
        else:
            return HttpResponse('校验失败')

    def post(self, request):
        try:
            data = request.body
            data = trans_xml_to_dict(data.decode())
            data = pkcs7_padding_encoder(data['Encrypt'])
            if data['MsgType'] == 'event':
                wyf_gzh_openid = data['FromUserName']
                if data['Event'] == 'subscribe':
                    logger.info(str(data))
                    """关注事件"""
                    access_token = wyf_access_token()
                    url = f'https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={wyf_gzh_openid}&lang=zh_CN'
                    response = requests.get(url=url)
                    result = response.json()
                    unionid = result['unionid']
                    user = CustomerUserVice.objects.filter(unionid=unionid).first()
                    if user:
                        user.wyf_gzh_openid = wyf_gzh_openid
                        user.is_subscribe = 1
                        user.save()
                    else:
                        user_data = {}
                        user_data['wyf_gzh_openid'] = wyf_gzh_openid
                        user_data['unionid'] = unionid
                        user_data['is_wyh_customer'] = 0
                        user_data['create_time'] = datetime.datetime.now()
                        user, create = CustomerUserVice.objects.get_or_create(defaults=user_data, unionid=unionid)
                        user.is_subscribe = 1
                        user.save()
                    if user.is_bind == 0:
                        result = bind_customer(unionid)
                        try:
                            if result['result_code'] == 'success':
                                user.is_bind = 1
                                user.save()
                        except:
                            pass
                elif data['Event'] == 'unsubscribe':
                    logger.info(str(data))
                    """取消关注事件"""
                    CustomerUserVice.objects.filter(wyf_gzh_openid=wyf_gzh_openid).update(is_subscribe=0)
                    return HttpResponse("")
        except Exception as e:
            logger.info(str(e))
            pass
        return HttpResponse("")


class WYHZSPublicAccountMessageView(APIView):

    def get(self, request, format=None):
        # 接收微信服务器get请求发过来的参数
        signature = request.GET.get('signature', None)
        timestamp = request.GET.get('timestamp', None)
        nonce = request.GET.get('nonce', None)
        echostr = request.GET.get('echostr', None)
        wechat_token = settings.WHYZS_TOKEN
        logger.info(f'{signature},{timestamp},{nonce},{echostr}')
        check_sign = get_sign_sha1([timestamp, nonce, wechat_token])
        if signature == check_sign:
            return HttpResponse(echostr)
        else:
            return HttpResponse('校验失败')

    def post(self, request):
        try:
            data = request.body
            print(data)
            data = trans_xml_to_dict(data.decode())
            data = pkcs7_padding_encoder(data['Encrypt'])
            # if data['MsgType'] == 'event':
            #     wyf_gzh_openid = data['FromUserName']
            #     if data['Event'] == 'subscribe':
            #         logger.info(str(data))
            #         """关注事件"""
            #         access_token = wyf_access_token()
            #         url = f'https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={wyf_gzh_openid}&lang=zh_CN'
            #         response = requests.get(url=url)
            #         result = response.json()
            #         unionid = result['unionid']
            #         user = CustomerUserVice.objects.filter(unionid=unionid).first()
            #         if user:
            #             user.wyf_gzh_openid = wyf_gzh_openid
            #             user.is_subscribe = 1
            #             user.save()
            #         else:
            #             user_data = {}
            #             user_data['wyf_gzh_openid'] = wyf_gzh_openid
            #             user_data['unionid'] = unionid
            #             user_data['is_wyh_customer'] = 0
            #             user_data['create_time'] = datetime.datetime.now()
            #             user, create = CustomerUserVice.objects.get_or_create(defaults=user_data, unionid=unionid)
            #             user.is_subscribe = 1
            #             user.save()
            #         if user.is_bind == 0:
            #             result = bind_customer(unionid)
            #             try:
            #                 if result['result_code'] == 'success':
            #                     user.is_bind = 1
            #                     user.save()
            #             except:
            #                 pass
            #     elif data['Event'] == 'unsubscribe':
            #         logger.info(str(data))
            #         """取消关注事件"""
            #         CustomerUserVice.objects.filter(wyf_gzh_openid=wyf_gzh_openid).update(is_subscribe=0)
            #         return HttpResponse("")
        except Exception as e:
            logger.info(str(e))
            pass
        return HttpResponse("")